import React, { useState, useEffect } from 'react';
import { useParams, Link, useNavigate } from 'react-router-dom';
import { Calendar, Clock, Tag, ArrowLeft, Lock, Eye, EyeOff, ChevronLeft, ChevronRight } from 'lucide-react';
import { marked } from 'marked';
import hljs from 'highlight.js';
import CryptoJS from 'crypto-js';
import { loadPostById, loadAllPosts } from '../utils/markdownLoader';
import { processCodeBlocks, initCopyHandlers } from '../utils/codeBlockProcessor';
import TableOfContents from '../components/TableOfContents';
import SEOHead from '../components/SEOHead';

const BlogPost = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [post, setPost] = useState(null);
  const [allPosts, setAllPosts] = useState([]);
  const [prevPost, setPrevPost] = useState(null);
  const [nextPost, setNextPost] = useState(null);
  const [loading, setLoading] = useState(true);
  const [password, setPassword] = useState('');
  const [isUnlocked, setIsUnlocked] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [error, setError] = useState('');

  useEffect(() => {
    // 重置所有状态
    setPost(null);
    setAllPosts([]);
    setPrevPost(null);
    setNextPost(null);
    setLoading(true);
    setPassword('');
    setIsUnlocked(false);
    setError('');

    // 配置 marked
    marked.setOptions({
      highlight: function(code, lang) {
        const language = hljs.getLanguage(lang) ? lang : 'plaintext';
        return hljs.highlight(code, { language }).value;
      },
      breaks: true,
      gfm: true,
      langPrefix: 'hljs language-'
    });

    // 加载文章和导航信息
    const loadPost = async () => {
      try {
        const [foundPost, posts] = await Promise.all([
          loadPostById(id),
          loadAllPosts()
        ]);
        
        if (foundPost) {
          setPost(foundPost);
          setAllPosts(posts);
          
          // 找到当前文章在列表中的位置
          const currentIndex = posts.findIndex(p => p.id === id);
          if (currentIndex !== -1) {
            // 设置上一篇和下一篇文章
            setPrevPost(currentIndex > 0 ? posts[currentIndex - 1] : null);
            setNextPost(currentIndex < posts.length - 1 ? posts[currentIndex + 1] : null);
          }
          
          // 只有非加密文章才自动解锁
          if (!foundPost.encrypted) {
            setIsUnlocked(true);
          }
        }
      } catch (error) {
        console.error('加载文章失败:', error);
      } finally {
        setLoading(false);
      }
    };
    
    loadPost();
  }, [id]);

  // 初始化复制功能
  useEffect(() => {
    if (post && isUnlocked) {
      // 延迟初始化，确保DOM已渲染
      const timer = setTimeout(() => {
        initCopyHandlers();
      }, 100);
      
      return () => clearTimeout(timer);
    }
  }, [post, isUnlocked]);

  const handlePasswordSubmit = (e) => {
    e.preventDefault();
    if (!password.trim()) {
      setError('请输入密码');
      return;
    }

    // 简单的密码验证（实际项目中应该使用更安全的方式）
    if (password === 'demo123') {
      setIsUnlocked(true);
      setError('');
    } else {
      setError('密码错误');
    }
  };

  const handleNavigateToPost = (targetPost) => {
    if (!targetPost) return;
    
    // 重置当前页面的解锁状态
    setIsUnlocked(false);
    setPassword('');
    setError('');
    
    // 跳转到目标文章
    navigate(`/blog/${targetPost.id}`);
  };

  const formatDate = (dateString) => {
    return new Date(dateString).toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });
  };

  if (loading) {
    return (
      <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
        <div className="animate-pulse">
          <div className="h-8 bg-gray-200 dark:bg-gray-700 rounded w-3/4 mb-4"></div>
          <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-1/2 mb-8"></div>
          <div className="space-y-3">
            <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded"></div>
            <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-5/6"></div>
            <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-4/6"></div>
          </div>
        </div>
      </div>
    );
  }

  if (!post) {
    return (
      <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-12 text-center">
        <h1 className="text-2xl font-bold text-gray-900 dark:text-white mb-4">
          文章未找到
        </h1>
        <Link
          to="/blog"
          className="inline-flex items-center text-spring-600 dark:text-spring-400 hover:text-spring-700 dark:hover:text-spring-300"
        >
          <ArrowLeft className="h-4 w-4 mr-2" />
          返回博客列表
        </Link>
      </div>
    );
  }

  // 如果是加密文章且未解锁，显示密码输入界面
  if (post.encrypted && !isUnlocked) {
    return (
      <>
        {post && (
          <SEOHead 
            title={post.title}
            description={post.excerpt}
            keywords={post.tags.join(', ')}
            type="article"
            publishedTime={post.date}
            author="技术博主"
          />
        )}
        <div className="max-w-2xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-8 text-center">
            <Lock className="h-16 w-16 text-yellow-500 mx-auto mb-6" />
            <h1 className="text-2xl font-bold text-gray-900 dark:text-white mb-4">
              {post.title}
            </h1>
            <p className="text-gray-600 dark:text-gray-300 mb-6">
              这是一篇加密文章，请输入密码查看内容
            </p>
            
            <form onSubmit={handlePasswordSubmit} className="max-w-sm mx-auto">
              <div className="relative mb-4">
                <input
                  type={showPassword ? "text" : "password"}
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  placeholder="请输入密码"
                  className="w-full px-4 py-3 pr-12 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-spring-500 focus:border-transparent"
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                >
                  {showPassword ? <EyeOff className="h-5 w-5" /> : <Eye className="h-5 w-5" />}
                </button>
              </div>
              
              {error && (
                <p className="text-red-500 text-sm mb-4">{error}</p>
              )}
              
              <button
                type="submit"
                className="w-full px-6 py-3 bg-spring-600 hover:bg-spring-700 text-white font-medium rounded-lg transition-colors"
              >
                解锁文章
              </button>
            </form>
            
            <Link
              to="/blog"
              className="inline-flex items-center mt-6 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300"
            >
              <ArrowLeft className="h-4 w-4 mr-2" />
              返回博客列表
            </Link>
          </div>
        </div>
      </>
    );
  }

  return (
    <>
      {post && (
        <SEOHead 
          title={post.title}
          description={post.excerpt}
          keywords={post.tags.join(', ')}
          type="article"
          publishedTime={post.date}
          author="技术博主"
        />
      )}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
        <div className="flex flex-col lg:flex-row gap-8">
          {/* Main Content */}
          <div className="flex-1 lg:max-w-4xl">
            {/* Back Button */}
            <Link
              to="/blog"
              className="inline-flex items-center mb-8 text-spring-600 dark:text-spring-400 hover:text-spring-700 dark:hover:text-spring-300 transition-colors"
            >
              <ArrowLeft className="h-4 w-4 mr-2" />
              返回博客列表
            </Link>

            {/* Article Header */}
            <header className="mb-8" itemScope itemType="https://schema.org/BlogPosting">
              <h1 className="text-4xl font-bold text-gray-900 dark:text-white mb-6" itemProp="headline">
                {post.title}
              </h1>
              
              <meta itemProp="datePublished" content={post.date} />
              <meta itemProp="author" content="技术博主" />
              <meta itemProp="description" content={post.excerpt} />
              
              <div className="flex flex-wrap items-center gap-6 text-sm text-gray-500 dark:text-gray-400 mb-6">
                <div className="flex items-center">
                  <Calendar className="h-4 w-4 mr-2" />
                  {formatDate(post.date)}
                </div>
                <div className="flex items-center">
                  <Clock className="h-4 w-4 mr-2" />
                  {post.readTime}
                </div>
                {post.encrypted && (
                  <div className="flex items-center text-yellow-600 dark:text-yellow-400">
                    <Lock className="h-4 w-4 mr-2" />
                    加密文章
                  </div>
                )}
              </div>

              <div className="flex flex-wrap gap-2">
                {post.tags.map(tag => (
                  <span
                    key={tag}
                    className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium"
                    style={{
                      backgroundColor: 'var(--color-primary-light)',
                      color: 'var(--color-primary-dark)'
                    }}
                  >
                    <Tag className="h-3 w-3 mr-1" />
                    {tag}
                  </span>
                ))}
              </div>
            </header>

            {/* Article Image */}
            {post.image && (
              <figure className="mb-8 rounded-xl overflow-hidden shadow-lg">
                <img
                  src={post.image}
                  alt={`${post.title}的配图`}
                  className="w-full h-64 md:h-96 object-cover"
                  itemProp="image"
                  loading="eager"
                />
              </figure>
            )}

            {/* Article Content */}
            <article className="prose prose-lg max-w-none markdown-content" itemProp="articleBody">
              <div dangerouslySetInnerHTML={{ __html: processCodeBlocks(marked(post.content)) }} />
            </article>

            {/* Article Navigation */}
            <nav className="mt-12 pt-8 border-t border-gray-200 dark:border-gray-700" aria-label="文章导航">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-8">
                {/* Previous Post */}
                {prevPost ? (
                  <button
                    onClick={() => handleNavigateToPost(prevPost)}
                    className="group flex items-center p-4 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg hover:shadow-md transition-all duration-200 w-full text-left"
                    style={{
                      '--hover-border-color': 'var(--color-primary)'
                    }}
                    onMouseEnter={(e) => {
                      e.currentTarget.style.borderColor = 'var(--color-primary)';
                    }}
                    onMouseLeave={(e) => {
                      e.currentTarget.style.borderColor = '';
                    }}
                  >
                    <div className="flex-shrink-0 mr-4">
                      <div 
                        className="w-10 h-10 rounded-full flex items-center justify-center transition-colors"
                        style={{
                          backgroundColor: 'var(--color-primary-light)'
                        }}
                      >
                        <ChevronLeft className="h-5 w-5" style={{ color: 'var(--color-primary)' }} />
                      </div>
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 mb-1">
                        <p className="text-sm text-gray-500 dark:text-gray-400">上一篇</p>
                        {prevPost.encrypted && (
                          <Lock className="h-3 w-3 text-yellow-500" />
                        )}
                      </div>
                      <h3 className="text-base font-medium text-gray-900 dark:text-white transition-colors line-clamp-2 group-hover:theme-color">
                        {prevPost.title}
                      </h3>
                    </div>
                  </button>
                ) : (
                  <div className="flex items-center p-4 bg-gray-50 dark:bg-gray-800/50 border border-gray-200 dark:border-gray-700 rounded-lg opacity-50">
                    <div className="flex-shrink-0 mr-4">
                      <div className="w-10 h-10 bg-gray-200 dark:bg-gray-700 rounded-full flex items-center justify-center">
                        <ChevronLeft className="h-5 w-5 text-gray-400" />
                      </div>
                    </div>
                    <div className="flex-1">
                      <p className="text-sm text-gray-400 dark:text-gray-500">没有更多文章了</p>
                    </div>
                  </div>
                )}

                {/* Next Post */}
                {nextPost ? (
                  <button
                    onClick={() => handleNavigateToPost(nextPost)}
                    className="group flex items-center p-4 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg hover:shadow-md transition-all duration-200 w-full text-left"
                    style={{
                      '--hover-border-color': 'var(--color-primary)'
                    }}
                    onMouseEnter={(e) => {
                      e.currentTarget.style.borderColor = 'var(--color-primary)';
                    }}
                    onMouseLeave={(e) => {
                      e.currentTarget.style.borderColor = '';
                    }}
                  >
                    <div className="flex-1 min-w-0 text-right">
                      <div className="flex items-center justify-end gap-2 mb-1">
                        <p className="text-sm text-gray-500 dark:text-gray-400">下一篇</p>
                        {nextPost.encrypted && (
                          <Lock className="h-3 w-3 text-yellow-500" />
                        )}
                      </div>
                      <h3 className="text-base font-medium text-gray-900 dark:text-white transition-colors line-clamp-2 group-hover:theme-color">
                        {nextPost.title}
                      </h3>
                    </div>
                    <div className="flex-shrink-0 ml-4">
                      <div 
                        className="w-10 h-10 rounded-full flex items-center justify-center transition-colors"
                        style={{
                          backgroundColor: 'var(--color-primary-light)'
                        }}
                      >
                        <ChevronRight className="h-5 w-5" style={{ color: 'var(--color-primary)' }} />
                      </div>
                    </div>
                  </button>
                ) : (
                  <div className="flex items-center p-4 bg-gray-50 dark:bg-gray-800/50 border border-gray-200 dark:border-gray-700 rounded-lg opacity-50">
                    <div className="flex-shrink-0 mr-4">
                      <div className="w-10 h-10 bg-gray-200 dark:bg-gray-700 rounded-full flex items-center justify-center">
                        <ChevronRight className="h-5 w-5 text-gray-400" />
                      </div>
                    </div>
                    <div className="flex-1">
                      <p className="text-sm text-gray-400 dark:text-gray-500">没有更多文章了</p>
                    </div>
                    <div className="flex-shrink-0 ml-4">
                      <div className="w-10 h-10 bg-gray-200 dark:bg-gray-700 rounded-full flex items-center justify-center">
                        <ChevronRight className="h-5 w-5 text-gray-400" />
                      </div>
                    </div>
                  </div>
                )}
              </div>
            </nav>

            {/* Article Footer */}
            <footer className="pt-6 border-t border-gray-200 dark:border-gray-700">
              <div className="flex justify-between items-center">
                <div className="text-sm text-gray-500 dark:text-gray-400">
                  最后更新：{formatDate(post.date)}
                </div>
                <Link
                  to="/blog"
                  className="inline-flex items-center px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
                >
                  查看更多文章
                </Link>
              </div>
            </footer>
          </div>

          {/* 目录侧边栏 */}
          <aside className="lg:w-80 lg:flex-shrink-0">
            <div className="lg:hidden mb-8">
              <TableOfContents content={post.content} />
            </div>
            <div className="hidden lg:block">
              <TableOfContents content={post.content} />
            </div>
          </aside>
        </div>
      </div>
    </>
    );
  };

  export default BlogPost;
